<template>
  <div id="box" style="">
    <!--顶部按钮-->
    <div style="height: 50px;line-height: 50px;">
      <el-row>
        <el-col align="right">
          <el-button @click="Add">添加</el-button>
          <el-button style="margin-left: 20px;" @click="Modify">修改</el-button>
          <el-button style="margin-left: 20px;" @click="Delet">删除</el-button>
        </el-col>
      </el-row>
      <el-dialog :visible.sync="modal1" title="添加新科室" align="center" width="40%">
        <el-form ref="Addition" :model="Addit" :rules="Addrule" label-width="110px">
          <div>
            <el-row>
              <!-- <el-col :span="20" :offset="1" style="margin-top: -14px;">
<el-form-item label="科室名称" prop="deptName">
<el-input v-model="Addit.deptName" clearable placeholder=""></el-input>
</el-form-item>
</el-col> -->
              <el-col :span="20" :offset="1" style="margin-top: -14px;">
                <el-form-item label="科室名称" prop="deptName">
                  <el-select v-model="Addit.deptName" clearable placeholder="" style="text-align: left">
                    <el-option v-for="item in deptMap" :key="item" :value="item">{{ item }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-if="Addit.deptName == '其他'" :span="20" :offset="1" style="margin-top: -14px;">
                <el-form-item label="科室名称" prop="deptOtherName">
                  <el-input v-model="Addit.deptOtherName" clearable placeholder="" />
                </el-form-item>
              </el-col>
              <el-col :span="20" :offset="1" style="margin-top: -14px;">
                <el-form-item label="科室编号" prop="deptsuffix">
                  <el-select v-model="Addit.suffix" clearable placeholder="后缀编号,非必填" style="text-align: left">
                    <el-option v-for="(item, index) in suffixMap" :key="item" :value="item">{{ index }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <div slot="footer">
          <el-row>
            <el-col style="text-align: center;" class="button">
              <el-button @click="Addcancel()">取消</el-button>
              <el-button style="margin-left: 30px;" class="sousuobtn" @click="Addconfirm('')">确认</el-button>
            </el-col>
          </el-row>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="modal2" title="修改科室信息" align="center" width="40%">
        <el-form ref="Mod" :model="Modit" :rules="Modrule" label-width="110px">
          <div>
            <el-row>
              <!-- <el-col :span="20" :offset="1" style="margin-top: -14px;">
<el-form-item label="科室名称">
<el-input v-model="Modit.name" clearable placeholder=""></el-input>
</el-form-item>
</el-col> -->
              <el-col :span="20" :offset="1" style="margin-top: -14px;">
                <el-form-item label="科室名称" prop="deptName">
                  <el-select v-model="Modit.deptName" clearable placeholder="" style="text-align: left">
                    <el-option v-for="item in deptMap" :key="item" :value="item">{{ item }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col v-if="Modit.deptName == '其他'" :span="20" :offset="1" style="margin-top: -14px;">
                <el-form-item label="科室名称" prop="deptOtherName"><el-input v-model="Modit.deptOtherName" clearable placeholder="" /></el-form-item>
              </el-col>
              <el-col :span="20" :offset="1" style="margin-top: -14px;">
                <el-form-item label="科室编号" prop="deptsuffix">
                  <el-select v-model="Modit.suffix" clearable placeholder="后缀编号,非必填" style="text-align: left">
                    <el-option v-for="(item, index) in suffixMap" :key="item" :value="item">{{ index }}</el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <div slot="footer">
          <el-row>
            <el-col style="text-align: center;" class="button">
              <el-button @click="Modcancel()">取消</el-button>
              <el-button style="margin-left: 30px;" class="sousuobtn" @click="Modconfirm('')">确认</el-button>
            </el-col>
          </el-row>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="modal3" title="删除科室信息" align="center" width="40%">
        <p style="font-size: 16px;">是否删除当前科室</p>
        <div slot="footer">
          <el-row>
            <el-col style="text-align: center;" class="button">
              <el-button @click="Deletcancel()">取消</el-button>
              <el-button style="margin-left: 30px;" class="sousuobtn" @click="Deletconfirm()">确认</el-button>
            </el-col>
          </el-row>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="modal4" title="人员信息" align="center" width="40%" :footer-hide="true">
        <br>
        <span>用户名：</span>
        <el-input v-model="searchusername" placeholder="用户名" style="width: 20%;" />
        <span>姓名：</span>
        <el-input v-model="searchnickname" placeholder="姓名" style="width: 20%;" />
        <span>状态：</span>
        <el-select v-model="searchstate" placeholder="请选择" style="width: 20%;margin-right: 10px;margin-bottom: 20px;">
          <el-option v-for="item in states" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button size="medium" type="primary" style="margin-bottom: 10px;" @click="searchrole()">查询</el-button>
        <el-table
          border
          max-height="700"
          highlight-current-row
          :data="
            data2
              .filter(
                data =>
                  (!searchroledata.username || data.username.toLowerCase().includes(searchroledata.username.toLowerCase())) &&
                  (!searchroledata.nickname || data.nickname.toLowerCase().includes(searchroledata.nickname.toLowerCase())) &&
                  (!searchroledata.state || data.state.toLowerCase().includes(searchroledata.state.toLowerCase()))
              )
              .slice((cPage - 1) * csize, cPage * csize)
          "
        >
          <el-table-column label="用户名" prop="username" />
          <el-table-column label="姓名" prop="nickname" />
          <el-table-column label="人员类型" prop="persontypename" />
          <el-table-column label="所属机构" prop="hospitalId" />
          <el-table-column label="状态" prop="state" />
        </el-table>
      </el-dialog>
    </div>
    <!--左侧树-->
    <div style="float: left; width: 270px;padding: 20px 0px;background-color: white;height: 680px;overflow:auto;">
      <el-tree
        ref="tree"
        :highlight-current="true"
        style="padding: 10px 10px;margin-top: 20px;border-top: 1px solid #E0E0E0;width: 100%;font-size:14px"
        :data="basedata"
        :props="defaultProps"
        default-expand-all
        @node-click="handleNodeClick"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>
            <i class="fa fa-file-text-o" style="color: orange;" />
            <span style="margin-left: 5px;">{{ node.label }}</span>
          </span>
        </span>
      </el-tree>
    </div>
    <!--右侧表格-->
    <div style="float: right; width: calc(100% - 280px);padding: 20px;background-color: white;">
      <el-form label-width="80px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="医院编码:" prop="hospitalId"><el-input v-model="hospitalId" clearable placeholder="" disabled /></el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="医院名称:" prop="hospitalName"><el-input v-model="hospitalName" clearable placeholder="" disabled /></el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-table border height="575" :data="data1" size="small" highlight-current-row overflow:auto :row-class-name="rowClassName" @row-click="clickdept">
              <el-table-column prop="id" label="科室编码" align="cebter" />
              <el-table-column prop="name" label="科室名称" align="cebter" />
              <el-table-column prop="hospitalId" label="所属机构" align="cebter" />
            </el-table>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script type="text/javascript">
import { queryTreeList, queryHospitalId, saveAdd, postUpdate, postDeptDelete, queryDeptUser } from '@/api/back-management/BG_dept'
export default {
  data() {
    return {
      temp: '', // 空
      // 树形结构数据，存在children中，暂无父级数据
      basedata: [],
      // 树子节点
      defaultProps: {
        children: 'children',
        // 显示的数据
        label: 'hospitalName'
      },
      // 查医院的
      curPage: 1, // 初始页
      pageSize: 10, //    每页的数据
      hospitalId: '',
      hospitalName: '',
      hosgrade: '',
      hospitalstate: '',
      areaCodeCounty: '',
      searchdeptname: '',
      searchtype: '',
      // 医院等级
      levelList: [],
      // 科室类型
      choseoption: [],
      // 科室信息表
      columnsCharge1: [
        {
          title: '科室编码',
          key: 'id',
          resizable: true,
          align: 'center'
        },
        {
          title: '科室名称',
          key: 'name',
          resizable: true,
          align: 'center'
        },
        {
          title: '所属机构',
          key: 'hospitalId',
          resizable: true,
          align: 'center'
        }
      ],
      data1: [],
      // 表单分页总数
      pageTotal: 0,
      // 从第一页开始
      pageNum: 1,
      // 每页显示多少条
      // pageSize: 15,
      // 新增科室弹窗
      modal1: false,
      // 新增科室表单
      Addit: {
        deptCode: '',
        deptName: '',
        deptOtherName: '',
        suffix: '',
        deptFlag: '',
        deptType: ''
      },
      // 新增所需信息
      AdditList: {
        hospitalId: '',
        deptCode: '',
        deptName: '',
        deptOtherName: '',
        suffix: '',
        deptFlag: '',
        deptType: ''
      },
      // 新增科室表单不能为空
      Addrule: {
        deptCode: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptName: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptOtherName: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptsuffix: [
          {
            required: false,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptFlag: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptType: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ]
      },
      // 修改科室信息弹窗
      modal2: false,
      // 修改科室表单
      Modit: {
        name: '',
        hospitalId: '',
        deptCode: '',
        deptId: '',
        deptName: '',
        deptOtherName: '',
        suffix: '',
        deptFlag: '',
        deptType: ''
      },
      // 修改科室表单不能为空
      Modrule: {
        deptCode: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptName: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptOtherName: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptsuffix: [
          {
            required: false,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptFlag: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        deptType: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ]
      },
      // 删除弹窗
      modal3: false,
      // 人员信息弹窗
      modal4: false,
      // 用户名
      searchusername: '',
      // 姓名
      searchnickname: '',
      // 状态
      searchstate: '',
      data2: [],
      // 人员信息
      cPage: 1, // 初始页
      csize: 10, //    每页的数据
      // 人员类型
      roletype: [],
      // 人员状态
      states: [
        {
          value: '有效',
          label: '有效'
        },
        {
          value: '无效',
          label: '无效'
        }
      ],
      searchroledata: {
        username: '',
        nickname: '',
        state: ''
      },
      userPage: 1, // 初始页
      usersize: 10, //    每页的数据
      deptMap: {
        神内科: '神内科',
        CT室: 'CT室',
        心内科: '心内科',
        心电图室: '心电图室',
        超声室: '超声室',
        其他: '其他'
      },
      suffixMap: {
        一: '一',
        二: '二',
        三: '三',
        四: '四',
        五: '五',
        六: '六',
        七: '七',
        八: '八',
        九: '九',
        十: '十'
      }
    }
  },
  created() {
    // 得到树
    this.getbasedata()
    // 医院级别
    // this.levelDropdown();
    // 科室类型
    // this.getalltypes();
  },
  methods: {
    // 得到树数据方法
    getbasedata() {
      this.getbase = {
        hospitalId: '0',
        type: '',
        hospitalName: ''
      }
      // const that = this
      const data = {
        token: this.$store.getters.token,
        start: this.curPage - 1,
        length: this.pageSize,
        parentId: 'root'
      }
      queryTreeList(data).then(res => {
        // res = JSON.parse(res)
        this.basedata = res
        console.log(res)
      })
    },
    // 单击左侧树获得数据方法
    handleNodeClick(data) {
      console.log(data)
      this.hospitalId = data.hospitalId
      this.hospitalName = data.hospitalName
      this.hosgrade = data.hosgrade
      this.hospitalstate = data.enabled + ''
      this.areaCodeCounty = data.areaCodeCounty
      this.selectChange(this.hospitalId)
    },
    // // 医院级别
    // levelDropdown() {
    //     var a = "HOSGRADE";
    //     $.ajax({
    //         method: "GET",
    //         url: '/api-his/his/commons/dictionary',
    //         params: {
    //             parent_type: a
    //         },
    //         headers: {
    //             'Content-Type': 'application/x-www-form-urlencoded',
    //             "Authorization": "Bearer " + localStorage.getItem("access_token")
    //         },
    //         withCredentials: true
    //     }).then((response) => {
    //         this.levelList = response.data;
    //     })
    // },
    // // 科室类型
    // getalltypes() {
    //     let that = this;
    //     $.ajax({
    //         method: "get",
    //         headers: {
    //             'Content-Type': 'application/json; charset=utf-8',
    //             "Authorization": "Bearer " + localStorage.getItem("access_token")
    //         },
    //         url: '/api-his/his/commons/dictionary?parent_type=DETP_TYPE',
    //     }).then(function (res) {
    //         res = res.data
    //         that.choseoption = res
    //     });
    // },
    // 查询表格
    selectChange(getbase) {
      const that = this
      console.log(getbase)
      // if (this.id == '' || this.id == undefined) {
      //     this.tableData = [];
      if (getbase === '' || getbase === undefined) {
        this.tableData = []
      } else {
        // debugger;

        const d = {
          start: 0.0,
          length: 999999,
          id: getbase,
          token: this.$store.getters.token,
          hospitalId: getbase
        }

        queryHospitalId(d).then(res => {
          // res = JSON.parse(res)
          res = res.data
          console.log('部门信息', res)
          this.data1 = res
          console.log('表格信息', that.data1)
        })
      }
      //
      // this.data1 = [];
      // let pageNum = this.pageNum;
      // let pageSize = this.pageSize;
      // let start = (pageNum - 1) * pageSize;
      // $.ajax({
      //     method: "GET",
      //     url: '/hospitalId',
      //     data: {
      //         deptName: this.searchdeptname,
      //         deptType: this.searchtype,
      //         start: start,
      //         length: pageSize,
      //         hospitalId: this.hospitalId,
      //         token: localStorage.getItem("access_token")
      //     },
      //     headers: {
      //         'Content-Type': 'application/x-www-form-urlencoded',
      //         "Authorization": "Bearer " + localStorage.getItem("access_token")
      //     },
      //     withCredentials: true
      // }).then((response) => {
      //     this.data1 = response.data.data;
      //     this.pageTotal = response.data.total;
      // })
    },
    // 获取分页数值
    handlePage(value) {
      this.pageNum = value
      this.selectChange()
    },
    // 获取分页条数
    handlePageSize(value) {
      this.pageSize = value
      this.selectChange()
    },
    // 控制新增弹窗
    Add() {
      if (this.hospitalId === '' || this.hospitalId === undefined) {
        this.$message({
          message: '请选择医院',
          type: 'warning'
        })
      } else {
        this.modal1 = true
        if (this.$refs['Addition'] !== undefined) {
          this.$refs['Addition'].resetFields()
        }
      }
    },
    // 新增确认
    Addconfirm() {
      // this.AdditList.hospitalId = this.hospitalId;
      // this.AdditList.deptCode = this.Addit.deptCode;
      // this.AdditList.deptName = this.Addit.deptName;
      // this.AdditList.deptFlag = this.Addit.deptFlag;
      // this.AdditList.deptType = this.Addit.deptType;
      // this.AdditList.token = localStorage.getItem("access_token");
      // console.log('this.AdditList', this.AdditList)
      this.$refs['Addition'].validate(valid => {
        if (valid) {
          const b = {
            hospitalId: this.hospitalId,
            deptCode: this.Addit.deptCode,
            deptName: (this.Addit.deptName === '其他' ? this.Addit.deptOtherName : this.Addit.deptName) + (this.Addit.suffix || ''),
            deptFlag: this.Addit.deptFlag,
            deptType: this.Addit.deptType,
            token: this.$store.getters.token
          }
          saveAdd(b)
            .then(response => {
              console.log(response)
              this.$message({
                message: '添加成功',
                type: 'success'
              })

              this.modal1 = false
              this.selectChange(this.hospitalId)
              this.$refs['Addition'].resetFields()
            })
            .catch(error => {
              console.log(error)
              this.$message({
                message: '添加失败',
                type: 'error'
              })
            })
        } else {
          this.$message({
            message: '请将必填项填写完整',
            type: 'error'
          })
          return
        }
      })
    },
    // 新增取消
    Addcancel() {
      this.modal1 = false
    },
    clickdept(data) {
      console.log(data)
      this.Modit = {
        name: '',
        hospitalId: '',
        deptCode: '',
        deptId: '',
        deptName: '',
        deptOtherName: '',
        suffix: '',
        deptFlag: '',
        deptType: ''
      }
      this.Modit.hospitalId = data.hospitalId
      this.Modit.deptCode = data.deptCode
      this.Modit.deptId = data.deptId
      this.Modit.deptFlag = data.deptFlag + ''
      this.Modit.deptType = data.deptType
      this.Modit.id = data.id
      this.Modit.name = data.name

      const name = data.name
      // this.Modit.deptName = data.deptName;
      let deptName = ''
      if (this.suffixMap[name.charAt(name.length - 1)]) {
        // 获取最后一位,看是否为 一~十结尾
        this.Modit.suffix = this.suffixMap[name.charAt(name.length - 1)] // 是 一~十 则赋值给Modit.suffix
        deptName = name.substring(0, name.length - 1) // 获取前置位
      } else {
        // 若 非一~十结尾
        deptName = name // 获取name
        this.Modit.suffix = ''
      }
      if (this.deptMap[deptName]) {
        // 如果是存在于固定列表中,(即存在于deptMap内,非其他手写部门名称)
        this.Modit.deptName = deptName // 直接为下拉框赋值
      } else {
        // 如果不是
        this.Modit.deptName = '其他' // 下拉框赋值为 "其他"
        this.Modit.deptOtherName = deptName // 则为输入框赋值
      }
      console.log(this.Modit)
    },
    // 控制修改弹窗
    Modify() {
      if (this.Modit.hospitalId === '' || this.Modit.hospitalId === undefined) {
        this.$message({
          message: '请选择科室',
          type: 'warning'
        })
      } else {
        this.modal2 = true
      }
    },
    // 确认修改
    Modconfirm() {
      const data = this.Modit
      // datas.token = localStorage.getItem("access_token")
      this.$refs['Mod'].validate(valid => {
        if (valid) {
          var b = {
            id: data.id,
            hospitalId: data.hospitalId,
            name: (data.deptName === '其他' ? data.deptOtherName : data.deptName) + (data.suffix || ''),
            // deptName: data.name,
            deptName: (data.deptName === '其他' ? data.deptOtherName : data.deptName) + (data.suffix || ''),
            token: this.$store.getters.token
          }
          console.log('发送数据', b)

          postUpdate(b)
            .then(response => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.modal2 = false
              this.$refs['Mod'].resetFields()
              this.Modit.hospitalId = ''
              this.selectChange(this.hospitalId)
            })
            .catch(error => {
              console.log(error)
              this.$message({
                message: '修改失败',
                type: 'error'
              })
            })
        } else {
          this.$message({
            message: '请将必填项填写完整',
            type: 'error'
          })
          return
        }
      })
    },
    // 修改取消
    Modcancel() {
      this.modal2 = false
    },
    // 控制删除弹窗
    Delet() {
      // console.log(this.Modit.hospitalId)
      if (this.Modit.hospitalId === '' || this.Modit.hospitalId === undefined) {
        this.$message({
          message: '请选择删除对象',
          type: 'warning'
        })
      } else {
        this.modal3 = true
      }
    },
    // 确认删除
    Deletconfirm() {
      var b = {
        id: this.Modit.id,
        token: this.$store.getters.token
      }

      postDeptDelete(b).then(response => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.modal3 = false
        // this.$refs['Mod'].resetFields()
        // this.$refs.Mod.validate()
        this.Modit.hospitalId = ''
        this.selectChange(this.hospitalId)
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '删除失败',
          type: 'error'
        })
      })
    },
    // 确认删除
    Deletcancel() {
      this.modal3 = false
    },
    // 控制人员信息弹窗
    Person() {
      if (this.Modit.hospitalId === '' || this.Modit.hospitalId === undefined) {
        this.$message({
          message: '请选择查看科室',
          type: 'warning'
        })
      } else {
        this.modal4 = true
        this.data2 = []
        var b = {
          deptId: this.Modit.id,
          id: this.Modit.id,
          hospitalId: this.Modit.hospitalId,
          start: this.cPage - 1,
          length: this.csize * 10000,
          token: this.$store.getters.token
        }
        // 人员类型
        this.gettype()

        queryDeptUser(b).then(response => {
          this.data2 = response.data.data
          for (let i = 0; i < this.data2.length; i++) {
            if (this.data2[i].enabled === true) {
              this.data2[i].state = '有效'
            } else {
              this.data2[i].state = '无效'
            }
            for (let a = 0; a < this.roletype.length; a++) {
              if (this.data2[i].persontype === this.roletype[a].code) {
                this.data2[i].persontypename = this.roletype[a].name
              }
            }
          }
        })

        // $.ajax({
        //   method: 'post',
        //   url: '/findUserOfDept',
        //   data: JSON.stringify(b),
        //   headers: {
        //     'Content-Type': 'application/json',
        //     Authorization: 'Bearer ' + localStorage.getItem('access_token')
        //   },
        //   withCredentials: true
        // // }).then(response => {})
      }
    },
    // 人员类型
    gettype() {
      // const that = this
      // $.ajax({
      //   method: 'get',
      //   url: '/api-his/his/commons/dictionary?parent_type=PERSON_TYPE'
      //   headers: {
      //     'Content-Type': 'application/json; charset=utf-8',
      //     Authorization: 'Bearer ' + localStorage.getItem('access_token')
      //   },
      // }).then(function(res) {
      //   res = res.data
      //   that.roletype = res
      // })
    },
    searchrole() {
      this.searchroledata.username = this.searchusername
      this.searchroledata.nickname = this.searchnickname
      this.searchroledata.state = this.searchstate
    },
    rowClassName(row, index) {
      return 'demo-table-info-row'
    }
  }
}
</script>
<style scoped>
body {
  background-color: #f2f2f2;
}
#box {
  background-color: #f2f2f2;
  width: 100%;
  height: 100%;
}
.el-select {
    display: inline-block;
    width: 100%;
}
</style>
